package cn.acewill.yxd.yunxundian.ui.sign;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mingle.widget.LoadingView;
import com.mingle.widget.ShapeLoadingDialog;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.EvaApdater;
import cn.acewill.yxd.yunxundian.componet.BaseFragment;
import cn.acewill.yxd.yunxundian.componet.CheckDataDialog;
import cn.acewill.yxd.yunxundian.model.CollegueSchedule;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.pubClass.RMainUtils;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.sign.Contract.MEvaluationView;
import cn.acewill.yxd.yunxundian.ui.sign.Presenter.MEvaPresenterIml;
import cn.finalteam.toolsfinal.AppCacheUtils;

/**
 * Created by xxx on 2018/1/11.
 */

public class EvaluationForMeFragment extends BaseFragment implements MEvaluationView {

    private int SHOP_SIGN_CODE = 100;
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());

    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce = false;
    private boolean isPrepared = false;
    private MEvaPresenterIml presenter;
    private RecyclerView myRecycleView;

    private EvaApdater adapter;
    private RelativeLayout loadingRel;
    private LinearLayout dateLayout;
    private String currentdate;  //YYYY-MM
    public static Boolean isRefresh = false;
    public static Boolean searchRefresh = false;
    private LinearLayout nodata;
    private List<RMain> rMains;
    private int loadFrom = 0;
    private int shopId = 0;


    public static EvaluationForMeFragment getInstance(int loadfrom,int shopid) {
        Bundle bundle = new Bundle();
        bundle.putInt("loadfrom",loadfrom);
        bundle.putInt("shopid",shopid);
        EvaluationForMeFragment fragment = new EvaluationForMeFragment();
        fragment.setArguments(bundle);
        return fragment;

    }

    public void initData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
         //   currentdate = bundle.getString("date");
            loadFrom = bundle.getInt("loadfrom",1);
            shopId = bundle.getInt("shopid",0);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initData();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.base_evaluation_view, container, false);
        myRecycleView = (RecyclerView) view.findViewById(R.id.myRecycle);
        myRecycleView.setLayoutManager(new LinearLayoutManager(view.getContext()));
        myRecycleView.setNestedScrollingEnabled(false);
        loadingRel = (RelativeLayout) view.findViewById(R.id.loadingRel);
        dateLayout = (LinearLayout) view.findViewById(R.id.dateLayout);
        nodata = view.findViewById(R.id.nodata);
        isPrepared = true;
        presenter = new MEvaPresenterIml(this);
        lazyLoad();
        return view;
    }


    @Override
    protected void lazyLoad() {
        if (isRefresh) { //activity日程数据刷新
            if (presenter!=null){
                if (loadFrom == 0){
                    //操作过快finish activity 下一进入闪退，结束防止被调用
                    presenter.loadMyDataByShop(shopId,MyEvaluationActivity.currentData);
                    presenter.loadScore();
                    isRefresh = false;
                }else{
                    presenter.loadMyData(MyEvaluationActivity.currentData);
                    presenter.loadScore();
                    isRefresh = false;
                }
            }
            return;
        }
        if (searchRefresh) { //检索的刷新
            if (adapter != null) {
                if (MyEvaluationActivity.searchText!=null) {
                    adapter.getFilter().filter(MyEvaluationActivity.searchText);
                    searchRefresh = false;
                }
            }
        }
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        //初始数据加载
        if (presenter!=null){
            if (loadFrom == 0){ //门店数据
                presenter.loadMyDataByShop(shopId,MyEvaluationActivity.currentData);
                presenter.loadScore();
            }else{  //个人数据
                presenter.loadMyData(MyEvaluationActivity.currentData);
                presenter.loadScore();
            }
        }
        mHasLoadedOnce = true;

    }

    @Override
    public void showLoadingView() {
        loadingRel.setVisibility(View.VISIBLE);
        dateLayout.setVisibility(View.GONE);
        nodata.setVisibility(View.GONE);
    }

    @Override
    public void hideLoadingView() {
        loadingRel.setVisibility(View.GONE);
        dateLayout.setVisibility(View.VISIBLE);
        nodata.setVisibility(View.GONE);
    }

    @Override
    public void updateAdapter(List<Schedule> rrList) {
        adapter = new EvaApdater(getContext(), rrList, new EvaApdater.OnBtnClickListener() {
            @Override
            public void dotaskListener(Schedule schedule) {
                //执行任务
                rMains = RMainUtils.getInstance().loadRMins(schedule.getID());
                if (rMains!=null){
                    int mainId = rMains.get(0).getQ().getID();
                   boolean value =  AppCacheUtils.getInstance(pubClass.CachePath,pubClass.CacheName).getBoolean(mainId+"",false);
                   if (value){
                       startActivity(new Intent(getContext(), EditEvaluationActivity.class).putExtra("schId", schedule.getID()));
                   }else{
                       //弹出提示
                       showTipDialog(rMains.get(0).getQ(),schedule);
                   }
                }else{
                    BaseActivity.showToast(getContext(),"数据错误");
                }
            }

            @Override
            public void signListener(Schedule schedule) {
                //门店签字
                Intent in = new Intent(getContext(), SignActivity.class);
                in.putExtra("rrschid", schedule.getID());
                startActivityForResult(in, SHOP_SIGN_CODE);
            }

            @Override
            public void submitListener(Schedule schedule) {
                //数据提交做判断
              //  checkReport(schedule.getID());
              boolean[] flag = CheckDataDialog.getInstance(getContext()).checkDataComplete(schedule.getID());
              if (flag!=null){
                  showTipDialog(schedule.getID(),flag);
              }else{
                  BaseActivity.showToast(getContext(),"数据错误");
              }
            }
            @Override
            public void shareListener(Schedule schedule) {
                //分享
            }

            @Override
            public void lookListener(Schedule schedule) {
                //查看
                Intent in = new Intent(getContext(), LookEvaDetialActivity.class)
                        .putExtra("schid", schedule.getID());
                startActivity(in);
            }

            @Override //发送 == 提交
            public void sendListener(Schedule schedule) {
                startActivity(new Intent(getContext(),SendMailActivity.class).putExtra("schId",schedule.getID()));

            }
        },0);
        myRecycleView.setAdapter(adapter);
        if (adapter != null) {
            adapter.getFilter().filter(MyEvaluationActivity.searchText);
        }
    }

    @Override
    public void loadCollegSch(List<CollegueSchedule> csList) {

    }

    @Override
    public void showNoData() {
        nodata.setVisibility(View.VISIBLE);
        dateLayout.setVisibility(View.GONE);
        loadingRel.setVisibility(View.GONE);
    }

    @Override
    public void refreshAdapter() {
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void requestErro() {
        BaseActivity.showToast(getContext(), "数据请求失败");
    }

    public void showTipDialog(final RMain.QBean qBean, final Schedule schedule) {
        if (qBean != null) {
            if (qBean.getDescription() != null && !TextUtils.isEmpty(qBean.getDescription())) { //空的直接跳转
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                View dview = LayoutInflater.from(getContext()).inflate(R.layout.normal_text_view, (ViewGroup) getActivity().getWindow().getDecorView(), false);
                builder.setView(dview);
                builder.setTitle("提示信息");
                TextView mytext = dview.findViewById(R.id.mytext);
                mytext.setGravity(Gravity.LEFT);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    mytext.setText(Html.fromHtml(qBean.getDescription(), Html.FROM_HTML_MODE_COMPACT));
                } else {
                    mytext.setText(Html.fromHtml(qBean.getDescription()));
                }

                builder.setPositiveButton("跳过", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(getContext(), EditEvaluationActivity.class).putExtra("schId", schedule.getID()));

                    }
                });
                builder.setNegativeButton("不再提示", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AppCacheUtils.getInstance(pubClass.CachePath,pubClass.CacheName).put(qBean.getID()+"",true);
                        startActivity(new Intent(getContext(), EditEvaluationActivity.class).putExtra("schId", schedule.getID()));

                    }
                });
                builder.show();
            }else{
                startActivity(new Intent(getContext(), EditEvaluationActivity.class).putExtra("schId", schedule.getID()));
            }
        }
    }


    //数据提交判断
    private void showTipDialog(final int schId,boolean[] need){
        if (!need[0]&&!need[1]&&!need[2]){
            startActivity(new Intent(getContext(),SendMailActivity.class).putExtra("schId",schId));
        }else{
            final Dialog dialog= new Dialog(getContext(),R.style.mydialog);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.eva_check_dialog, (ViewGroup) getActivity().getWindow().getDecorView(),false);
            TextView addFollow = view.findViewById(R.id.addFollow);
            TextView shopSign = view.findViewById(R.id.shopSign);
            TextView jiBenData = view.findViewById(R.id.jiBenData);
            TextView gotoSubmit = view.findViewById(R.id.gotoSubmit);
            gotoSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getContext(),SendMailActivity.class).putExtra("schId",schId));
                }
            });
            TextView cancel_action = view.findViewById(R.id.cancel_action);
            cancel_action.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startActivity(new Intent(getContext(),EditEvaluationActivity.class).putExtra("schId",schId));
                }
            });
            if (!need[0]){
                addFollow.setVisibility(View.GONE);
            }
            if (!need[1]){
                shopSign.setVisibility(View.GONE);
            }
            if (!need[2]){
                jiBenData.setVisibility(View.GONE);
            }
            dialog.setContentView(view);
            dialog.setCancelable(true);
            dialog.show();
        }
    }


}


